import { IParamsResult } from '@/shared/core/decorator/ListParams.decorator'
import { HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'
import { CreateAppDto } from './dto/create-app.dto'
import { UpdateAppDto } from './dto/update-app.dto'
import { AppInfoEntity } from './entities/app.entity'

@Injectable()
export class AppService {
  constructor(
    @InjectRepository(AppInfoEntity)
    private readonly appInfoRepository: Repository<AppInfoEntity>,
  ) {}

  // 新增
  async create(dto: CreateAppDto) {
    const result = await this.appInfoRepository.create(dto)
    await this.appInfoRepository.save(result)

    return result
  }

  // 列表
  findAll({ pageParams, where, order }: IParamsResult) {
    const { page, limit } = pageParams

    return this.appInfoRepository.findAndCount({
      order,
      where,
      skip: (page - 1) * limit,
      take: limit,
    })
  }

  // 详情
  findOne(id) {
    return this.appInfoRepository.findOne({ where: { id } })
  }

  // 修改
  async update(id, dto: UpdateAppDto) {
    const old = await this.findOne(id)
    const vo = await this.appInfoRepository.merge(old, dto)

    return this.appInfoRepository.save(vo)
  }

  // 删除
  async remove(id) {
    const result = await this.appInfoRepository.delete(id)
    Logger.log(`删除返回数据：${JSON.stringify(result)}`)

    return result.affected || new HttpException('无法删除，请稍候在试', HttpStatus.BAD_REQUEST)
  }
}
